<template>
  <div class="encasement-dialog">
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="1000"
      destroy-on-close
      class="encasement-dialog__panel"
    >
      <div class="encasement-dialog__body">
        <el-scrollbar max-height="70vh">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="110px"
            class="encasement-form"
          >
            <el-alert
              v-if="ruleForm.autoCode"
              type="info"
              show-icon
              class="encasement-form__alert"
              title="系统自动生成装箱单编号，可在关闭开关后手动修改"
            />

            <div class="encasement-hero">
              <div class="encasement-hero__text">
                <p class="hero-title">装箱单信息录入</p>
                <p class="hero-desc">{{ completionTips }}</p>
                <div class="hero-tags">
                  <el-tag
                    :type="completionStatus.type"
                    effect="light"
                    size="small"
                    class="hero-tag"
                  >
                    {{ completionStatus.text }}
                  </el-tag>
                  <el-tag
                    :type="codeModeTagType"
                    effect="plain"
                    size="small"
                    class="hero-tag"
                  >
                    {{ ruleForm.autoCode ? "系统编号模式" : "手动编号模式" }}
                  </el-tag>
                </div>
              </div>
              <div class="hero-progress">
                <el-progress
                  type="circle"
                  :percentage="completionPercent"
                  :status="heroProgressStatus"
                  :width="94"
                  :stroke-width="8"
                />
                <span class="hero-progress__label">完善度</span>
              </div>
            </div>

            <el-steps
              :active="currentStep"
              finish-status="success"
              align-center
              class="form-steps"
            >
              <el-step title="基础信息" description="填写编号与客户" />
              <el-step title="装箱信息" description="输入尺寸重量" />
              <el-step title="确认提交" description="核对后提交" />
            </el-steps>

            <section class="summary-section">
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="8">
                  <el-card shadow="never" class="stat-card">
                    <p class="stat-label">预估体积</p>
                    <p class="stat-value">
                      {{ boxVolumeDisplay }}
                      <span v-if="hasVolumeValue" class="stat-unit">cm³</span>
                    </p>
                    <p class="stat-desc">长度 × 宽度 × 高度</p>
                  </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8">
                  <el-card shadow="never" class="stat-card stat-card--accent">
                    <p class="stat-label">重量信息</p>
                    <p class="stat-value">
                      {{ ruleForm.netWeight || "—" }}
                      <span class="stat-unit">kg</span>
                    </p>
                    <p class="stat-desc">
                      毛重 {{ ruleForm.grossWeight || "—" }}kg · 差值
                      <span class="stat-highlight">{{ weightGapDisplay }}</span
                      >kg
                    </p>
                  </el-card>
                </el-col>
                <el-col :xs="24" :sm="24" :md="8">
                  <el-card shadow="never" class="stat-card">
                    <p class="stat-label">客户绑定</p>
                    <p class="stat-value stat-value--text">
                      {{ ruleForm.customerName || "待选择客户" }}
                    </p>
                    <el-tag
                      :type="hasCustomerSelected ? 'success' : 'info'"
                      size="small"
                    >
                      {{ ruleForm.customerCode || "暂无编号" }}
                    </el-tag>
                    <p class="stat-desc">绑定客户后可快速回溯</p>
                  </el-card>
                </el-col>
              </el-row>
            </section>

            <section class="form-section">
              <header class="section-header">
                <div class="section-header__main">
                  <el-icon class="section-header__icon">
                    <DocumentAdd />
                  </el-icon>
                  <div>
                    <p class="section-title">基础信息</p>
                    <p class="section-subtitle">完善装箱单的基础内容</p>
                  </div>
                </div>
                <el-tag type="success" effect="light" size="small">
                  必填字段
                </el-tag>
              </header>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item
                    label="装箱单编号"
                    prop="packingListNo"
                    required
                  >
                    <div class="inline-field">
                      <el-input
                        v-model="ruleForm.packingListNo"
                        :disabled="ruleForm.autoCode"
                        placeholder="请输入/自动生成"
                      />
                      <el-tooltip
                        content="开启后系统将基于时间戳生成唯一编号"
                        placement="top"
                      >
                        <el-switch
                          v-model="ruleForm.autoCode"
                          @change="handleAutoCodeChange"
                        />
                      </el-tooltip>
                      <span class="inline-field__label">系统编号</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="装箱单名称"
                    prop="packingListName"
                    required
                  >
                    <el-input
                      v-model="ruleForm.packingListName"
                      placeholder="如：11月订单-客户A"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="装箱日期" prop="packingDate" required>
                    <el-date-picker
                      v-model="ruleForm.packingDate"
                      type="date"
                      placeholder="请选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="订单编号(销售)" prop="salesOrderNo">
                    <el-input
                      v-model="ruleForm.salesOrderNo"
                      placeholder="请输入关联订单"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户名称" prop="customerId" required>
                    <div class="customer-picker">
                      <el-input
                        v-model="ruleForm.customerName"
                        placeholder="请选择客户"
                        readonly
                      />
                      <el-button
                        type="primary"
                        plain
                        class="customer-picker__btn"
                        @click="openCustomerDialog"
                      >
                        <el-icon><Postcard /></el-icon>
                      </el-button>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户编号" prop="customerCode">
                    <el-input
                      v-model="ruleForm.customerCode"
                      placeholder="请选择客户后生成"
                      readonly
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input
                      v-model="ruleForm.remark"
                      type="textarea"
                      :rows="3"
                      placeholder="可补充发货、包装等信息"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </section>

            <section class="form-section">
              <header class="section-header">
                <div class="section-header__main">
                  <el-icon class="section-header__icon">
                    <Box />
                  </el-icon>
                  <div>
                    <p class="section-title">装箱信息</p>
                    <p class="section-subtitle">录入尺寸及重量数据</p>
                  </div>
                </div>
                <el-tag type="info" effect="plain" size="small"> 可选 </el-tag>
              </header>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="箱子长度(CM)" prop="boxLength">
                    <el-input
                      v-model="ruleForm.boxLength"
                      type="number"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="箱子宽度(CM)" prop="boxWidth">
                    <el-input
                      v-model="ruleForm.boxWidth"
                      type="number"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="箱子高度(CM)" prop="boxHeight">
                    <el-input
                      v-model="ruleForm.boxHeight"
                      type="number"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="净重(KG)" prop="netWeight">
                    <el-input
                      v-model="ruleForm.netWeight"
                      type="number"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="毛重(KG)" prop="grossWeight">
                    <el-input
                      v-model="ruleForm.grossWeight"
                      type="number"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="包含子箱" prop="hasSubBoxes">
                    <el-switch v-model="ruleForm.hasSubBoxes" />
                  </el-form-item>
                </el-col>
              </el-row>
            </section>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">
            关闭
          </el-button>
          <el-button type="success" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="customerDialogVisible"
      title="选择客户"
      width="900px"
      append-to-body
    >
      <el-card shadow="never" class="customer-card">
        <template #header>
          <div class="customer-card__header">
            <div class="customer-card__title">
              <el-icon><UserFilled /></el-icon>
              <span>客户筛选</span>
            </div>
            <span class="customer-card__tips">支持编号/名称模糊搜索</span>
          </div>
        </template>

        <div class="customer-search-bar">
          <el-input
            v-model="customerSearchForm.keyword"
            placeholder="客户编号/名称"
            clearable
            class="customer-search-bar__input"
          />
          <el-input
            v-model="customerSearchForm.type"
            placeholder="客户类型"
            clearable
            class="customer-search-bar__input"
          />
          <div class="customer-search-bar__actions">
            <el-button type="primary" @click="handleCustomerSearch">
              查询
            </el-button>
            <el-button @click="resetCustomerSearch">重置</el-button>
          </div>
        </div>

        <el-table
          v-loading="customerLoading"
          :data="customerTableData"
          height="360px"
          @row-click="onCustomerRowClick"
          border
          stripe
        >
          <el-table-column label="" width="60" align="center">
            <template #default="{ row }">
              <el-radio v-model="selectedCustomerId" :label="row.id" />
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="code" label="客户编号" min-width="160" />
          <el-table-column prop="name" label="客户名称" min-width="160" />
          <el-table-column prop="type" label="客户类型" min-width="120" />
          <el-table-column prop="contact" label="联系人" min-width="120" />
          <el-table-column prop="phone" label="联系电话" min-width="150" />
        </el-table>
      </el-card>

      <div class="customer-pagination">
        <el-pagination
          v-model:current-page="customerPagination.pageIndex"
          v-model:page-size="customerPagination.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="customerPagination.totalCount"
          small
          @size-change="onCustomerPageSizeChange"
          @current-change="onCustomerPageChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="customerDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!selectedCustomerId"
            @click="confirmCustomerSelection"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  Postcard,
  DocumentAdd,
  Box,
  UserFilled,
} from "@element-plus/icons-vue";
import https from "@/Http/http";

// Props
const props = defineProps<{
  modelValue: boolean;
  editData?: any;
}>();

// Emits
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  success: [];
}>();

const title = ref("创建装箱单");
const ruleFormRef = ref<FormInstance>();

// 对话框显示状态
const dialogFormVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => {
    emit("update:modelValue", val);
  },
});

// 基于时分秒生成编码的辅助函数
// 使用时间戳和计数器确保每次生成都不同
let encasementCodeGenerationCounter = 0; // 全局计数器，确保每次生成都不同

const generateEncasementCodeByTime = (): void => {
  // 立即获取当前时间，确保每次调用都获取最新时间
  const now = new Date();
  const pad = (n: number, len: number = 2) => `${n}`.padStart(len, "0");

  // 获取时分秒和完整毫秒
  const hours = pad(now.getHours());
  const minutes = pad(now.getMinutes());
  const seconds = pad(now.getSeconds());
  const milliseconds = now.getMilliseconds();

  // 获取当前时间戳（毫秒级）
  const timestamp = Date.now();

  // 获取高精度时间（如果可用）
  let microSeconds = 0;
  if (typeof performance !== "undefined" && performance.now) {
    // performance.now() 返回自页面加载以来的毫秒数，包含小数部分（微秒级精度）
    const perfNow = performance.now();
    // 将微秒部分转换为整数（0-999）
    microSeconds = Math.floor((perfNow % 1) * 1000);
  } else {
    // 如果没有 performance API，使用随机数
    microSeconds = Math.floor(Math.random() * 1000);
  }

  // 递增计数器，确保即使在同一毫秒内也能生成不同的编码
  encasementCodeGenerationCounter =
    (encasementCodeGenerationCounter + 1) % 100000;

  // 生成唯一因子：使用时间戳的后4位 + 微秒的3位 + 计数器的后3位
  // 这样可以确保每次生成都不同
  const timestampSuffix = timestamp.toString().slice(-4).padStart(4, "0");
  const microSecondsStr = microSeconds.toString().padStart(3, "0");
  const counterStr = encasementCodeGenerationCounter
    .toString()
    .padStart(5, "0");
  const counterSuffix = counterStr.slice(-3);

  // 组合唯一因子：时间戳后4位 + 微秒3位 + 计数器后3位 = 10位，取后6位
  const uniqueFactor = (
    timestampSuffix +
    microSecondsStr +
    counterSuffix
  ).slice(-6);

  // 生成格式：ZXD + 年月日 + 时分秒 + 完整毫秒(3位) + 唯一因子(6位)
  // 格式示例：ZXD202411131430521234567890（年月日时分秒毫秒唯一因子）
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const msStr = pad(milliseconds, 3); // 完整3位毫秒

  // 组合：ZXD + 年月日(8位) + 时分秒(6位) + 毫秒(3位) + 唯一因子(6位) = 24位
  ruleForm.packingListNo =
    "ZXD" +
    year +
    month +
    day +
    hours +
    minutes +
    seconds +
    msStr +
    uniqueFactor;
};

// 系统编号开关变化
const handleAutoCodeChange = async (v: boolean): Promise<void> => {
  if (v) {
    // 开启系统编号时，每次都会生成新的编码（基于当前时分秒）
    // 先清空编码，确保每次都生成新的
    ruleForm.packingListNo = "";

    // 直接调用生成函数，立即获取当前时间并生成编码
    // 不延迟，确保每次调用都获取最新的时间戳
    generateEncasementCodeByTime();

    // 调试：输出生成的编码（开发时可以查看）
    console.log(
      "生成的装箱单编码:",
      ruleForm.packingListNo,
      "计数器:",
      encasementCodeGenerationCounter,
      "时间戳:",
      Date.now()
    );
  } else {
    // 关闭系统编号时，保留当前编码，允许用户手动修改
    // 不清空编码，让用户可以基于当前编码进行修改
  }
};

interface CustomerRow {
  id: number;
  code: string;
  name: string;
  type?: string;
  contact?: string;
  phone?: string;
}

const customerDialogVisible = ref(false);
const customerLoading = ref(false);
const customerTableData = ref<CustomerRow[]>([]);
const selectedCustomerId = ref<number | null>(null);
const customerSearchForm = reactive({
  keyword: "",
  type: "",
});
const customerPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const openCustomerDialog = () => {
  customerDialogVisible.value = true;
  customerPagination.pageIndex = 1;
  selectedCustomerId.value = ruleForm.customerRowId;
  fetchCustomerList();
};

const mapToCustomerRow = (row: any): CustomerRow => {
  const id = Number(row.id ?? row.ID ?? row.customerId ?? 0);
  const code =
    row.custnumber ??
    row.custNumber ??
    row.customerCode ??
    row.customer_code ??
    row.code ??
    "";
  const name =
    row.custname ??
    row.custName ??
    row.customerName ??
    row.customer_name ??
    row.name ??
    "";
  const type =
    row.custtype ?? row.custType ?? row.customerType ?? row.type ?? "";
  const contact = row.people ?? row.People ?? row.contact ?? row.linkman ?? "";
  const phone = row.phone ?? row.tel ?? row.mobile ?? row.telephone ?? "";

  return {
    id,
    code,
    name,
    type,
    contact,
    phone,
  };
};

const fetchCustomerList = () => {
  customerLoading.value = true;
  const params: Record<string, any> = {
    pageindex: customerPagination.pageIndex,
    pagesize: customerPagination.pageSize,
  };
  if (customerSearchForm.keyword) {
    params.name = customerSearchForm.keyword;
  }
  if (customerSearchForm.type) {
    params.type = customerSearchForm.type;
  }
  https.Reads.get("/Cust/ShowCust", { params })
    .then((res: any) => {
      if (res.data.code === 1) {
        const list = Array.isArray(res.data.data) ? res.data.data : [];
        customerTableData.value = list.map(mapToCustomerRow);
        customerPagination.totalCount = res.data.totalCount || 0;
        customerPagination.pageCount = res.data.pageCount || 0;
      } else {
        customerTableData.value = [];
        customerPagination.totalCount = 0;
        ElMessage.error(res.data.msg || "获取客户列表失败");
      }
    })
    .catch((error: any) => {
      console.error("获取客户列表失败:", error);
      customerTableData.value = [];
      customerPagination.totalCount = 0;
      ElMessage.error("获取客户列表失败，请稍后重试");
    })
    .finally(() => {
      customerLoading.value = false;
    });
};

const handleCustomerSearch = () => {
  customerPagination.pageIndex = 1;
  fetchCustomerList();
};

const resetCustomerSearch = () => {
  customerSearchForm.keyword = "";
  customerSearchForm.type = "";
  handleCustomerSearch();
};

const onCustomerPageChange = (page: number) => {
  customerPagination.pageIndex = page;
  fetchCustomerList();
};

const onCustomerPageSizeChange = (size: number) => {
  customerPagination.pageSize = size;
  customerPagination.pageIndex = 1;
  fetchCustomerList();
};

const onCustomerRowClick = (row: CustomerRow) => {
  selectedCustomerId.value = row.id;
};

const confirmCustomerSelection = () => {
  const selected = customerTableData.value.find(
    (item) => item.id === selectedCustomerId.value
  );
  if (!selected) {
    ElMessage.warning("请选择客户");
    return;
  }
  ruleForm.customerRowId = selected.id;
  ruleForm.customerId = selected.name;
  ruleForm.customerName = selected.name;
  ruleForm.customerCode = selected.code;
  customerDialogVisible.value = false;
};

// 表单数据
interface EncasementForm {
  packingListId: number;
  packingListNo: string;
  packingListName: string;
  packingDate: string | Date;
  salesOrderNo: string;
  customerId: string;
  customerRowId: number | null;
  customerName: string;
  customerCode: string;
  remark: string;
  boxLength: string;
  boxWidth: string;
  boxHeight: string;
  netWeight: string;
  grossWeight: string;
  hasSubBoxes: boolean;
  autoCode: boolean;
}

const ruleForm = reactive<EncasementForm>({
  packingListId: 0,
  packingListNo: "",
  packingListName: "",
  packingDate: "" as string | Date,
  salesOrderNo: "",
  customerId: "",
  customerRowId: null as number | null,
  customerName: "",
  customerCode: "",
  remark: "",
  boxLength: "",
  boxWidth: "",
  boxHeight: "",
  netWeight: "",
  grossWeight: "",
  hasSubBoxes: false,
  autoCode: false,
});

const baseRequiredFields: (keyof EncasementForm)[] = [
  "packingListNo",
  "packingListName",
  "packingDate",
  "customerId",
];
const packingFields: (keyof EncasementForm)[] = [
  "boxLength",
  "boxWidth",
  "boxHeight",
  "netWeight",
  "grossWeight",
];

const getFilledCount = (fields: (keyof EncasementForm)[]) =>
  fields.filter((key) => {
    const value = ruleForm[key];
    if (typeof value === "boolean") {
      return value;
    }
    return value !== "" && value !== null && value !== undefined;
  }).length;

const completionPercent = computed(() => {
  const totalFields = baseRequiredFields.length + packingFields.length;
  if (!totalFields) return 0;
  const filled =
    getFilledCount(baseRequiredFields) + getFilledCount(packingFields);
  return Math.min(100, Math.round((filled / totalFields) * 100));
});

const completionStatus = computed(() => {
  if (completionPercent.value >= 90) {
    return { text: "信息完善", type: "success" };
  }
  if (completionPercent.value >= 60) {
    return { text: "继续补充", type: "warning" };
  }
  return { text: "待完善", type: "info" };
});

const completionTips = computed(() => {
  if (completionPercent.value >= 90) {
    return "所有关键字段已填写，可直接提交生成装箱单。";
  }
  if (completionPercent.value >= 60) {
    return "基础信息已齐全，再补充箱体与重量信息即可。";
  }
  return "先填写基础信息，系统会实时同步进度。";
});

const currentStep = computed(() => {
  if (completionPercent.value >= 90) return 3;
  if (completionPercent.value >= 60) return 2;
  return 1;
});

const heroProgressStatus = computed(() => {
  if (completionPercent.value >= 90) return "success";
  if (completionPercent.value >= 60) return "warning";
  return "exception";
});

const codeModeTagType = computed(() =>
  ruleForm.autoCode ? "primary" : "info"
);

const hasCustomerSelected = computed(() => Boolean(ruleForm.customerName));

const hasVolumeValue = computed(
  () =>
    Boolean(ruleForm.boxLength) &&
    Boolean(ruleForm.boxWidth) &&
    Boolean(ruleForm.boxHeight)
);

const boxVolume = computed(() => {
  if (!hasVolumeValue.value) return 0;
  const length = Number(ruleForm.boxLength) || 0;
  const width = Number(ruleForm.boxWidth) || 0;
  const height = Number(ruleForm.boxHeight) || 0;
  return length * width * height;
});

const boxVolumeDisplay = computed(() =>
  hasVolumeValue.value ? boxVolume.value.toLocaleString() : "—"
);

const hasWeightValues = computed(
  () => Boolean(ruleForm.netWeight) && Boolean(ruleForm.grossWeight)
);

const weightDiff = computed(() => {
  const gross = Number(ruleForm.grossWeight) || 0;
  const net = Number(ruleForm.netWeight) || 0;
  return gross - net;
});

const weightGapDisplay = computed(() => {
  if (!hasWeightValues.value) return "—";
  const diff = weightDiff.value;
  return Number.isInteger(diff) ? diff.toString() : diff.toFixed(2);
});

// 表单验证规则
const rules = reactive<FormRules>({
  packingListNo: [
    { required: true, message: "装箱单编号不可为空", trigger: "blur" },
  ],
  packingListName: [
    { required: true, message: "装箱单名称不可为空", trigger: "blur" },
  ],
  packingDate: [
    { required: true, message: "装箱日期不可为空", trigger: "change" },
  ],
  customerId: [
    { required: true, message: "客户名称不可为空", trigger: "change" },
  ],
});

// 打开对话框
const openDialog = () => {
  if (props.editData) {
    // 编辑模式
    title.value = "编辑装箱单";
    Object.assign(ruleForm, props.editData);
    ruleForm.autoCode = false; // 编辑时默认关闭自动生成
    ruleForm.customerName =
      props.editData.customerName ||
      props.editData.customer_name ||
      props.editData.customerCode ||
      "";
    ruleForm.customerId =
      props.editData.customerId || ruleForm.customerName || "";
    ruleForm.customerRowId = props.editData.customerRowId || null;
    if (!ruleForm.customerCode && props.editData.customerCode) {
      ruleForm.customerCode = props.editData.customerCode;
    }
  } else {
    // 新增模式
    title.value = "创建装箱单";
    resetForm();
    ruleForm.autoCode = true; // 默认开启自动生成
    // 打开对话框后自动生成编码（基于当前时分秒）
    setTimeout(() => {
      if (ruleForm.autoCode) {
        generateEncasementCodeByTime();
      }
    }, 150);
  }
};

// 重置表单
const resetForm = () => {
  ruleForm.packingListId = 0;
  ruleForm.packingListNo = "";
  ruleForm.packingListName = "";
  ruleForm.packingDate = "";
  ruleForm.salesOrderNo = "";
  ruleForm.customerId = "";
  ruleForm.customerRowId = null;
  ruleForm.customerName = "";
  ruleForm.customerCode = "";
  ruleForm.remark = "";
  ruleForm.boxLength = "";
  ruleForm.boxWidth = "";
  ruleForm.boxHeight = "";
  ruleForm.netWeight = "";
  ruleForm.grossWeight = "";
  ruleForm.hasSubBoxes = false;
  ruleForm.autoCode = false;
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 构建装箱明细数据（将装箱信息转换为明细）
      const detailDto = {
        PackingListId: 0, // 新增时设为0，后端会自动设置
        BoxLength: ruleForm.boxLength
          ? parseInt(String(ruleForm.boxLength))
          : 0,
        BoxWidth: ruleForm.boxWidth ? parseInt(String(ruleForm.boxWidth)) : 0,
        BoxHeight: ruleForm.boxHeight
          ? parseInt(String(ruleForm.boxHeight))
          : 0,
        NetWeight: ruleForm.netWeight
          ? parseInt(String(ruleForm.netWeight))
          : 0,
        GrossWeight: ruleForm.grossWeight
          ? parseInt(String(ruleForm.grossWeight))
          : 0,
        HasSubBox: ruleForm.hasSubBoxes || false,
      };

      // 处理日期格式：如果 packingDate 是字符串，转换为 ISO 格式
      let packingDateValue: string = "";
      if (ruleForm.packingDate) {
        if (typeof ruleForm.packingDate === "string") {
          // 如果是 YYYY-MM-DD 格式，转换为完整的 ISO 日期时间格式
          if (ruleForm.packingDate.match(/^\d{4}-\d{2}-\d{2}$/)) {
            packingDateValue = new Date(
              ruleForm.packingDate + "T00:00:00"
            ).toISOString();
          } else {
            // 如果已经是 ISO 格式，直接使用
            packingDateValue = ruleForm.packingDate;
          }
        } else if (ruleForm.packingDate instanceof Date) {
          packingDateValue = ruleForm.packingDate.toISOString();
        } else {
          // 其他情况，尝试转换为字符串
          packingDateValue = String(ruleForm.packingDate);
        }
      } else {
        // 如果没有选择日期，使用当前日期
        packingDateValue = new Date().toISOString();
      }

      // 构建请求数据，符合后端 EncasementAddCommand 结构
      const requestData = {
        encasementDto: {
          PackingListNo: ruleForm.packingListNo,
          PackingListName: ruleForm.packingListName,
          PackingDate: packingDateValue,
          SalesOrderNo: ruleForm.salesOrderNo || "",
          CustomerId: ruleForm.customerId || "",
          CustomerCode: ruleForm.customerCode || "",
          Remarks: ruleForm.remark || "",
          detailDtos: [detailDto], // 明细列表，至少需要一个
        },
      };

      if (ruleForm.packingListId === 0) {
        // 新增
        https.Writes.post("/Warehouse/EncasementAdd", requestData)
          .then((res: any) => {
            if (res.data.code === 1) {
              ElMessage.success(res.data.msg || "创建成功");
              dialogFormVisible.value = false;
              emit("success");
            } else {
              ElMessage.error(res.data.msg || "创建失败");
            }
          })
          .catch((error: any) => {
            console.error("创建失败:", error);
            ElMessage.error(
              error.response?.data?.msg || "创建失败，请稍后重试"
            );
          });
      } else {
        // 编辑 - 需要构建更新请求数据
        const updateData = {
          encasementDto: {
            ...requestData.encasementDto,
            // 编辑时需要包含ID等信息，根据实际后端接口调整
          },
        };
        https.Writes.put("/Warehouse/EncasementUpdate", updateData)
          .then((res: any) => {
            if (res.data.code === 1) {
              ElMessage.success(res.data.msg || "更新成功");
              dialogFormVisible.value = false;
              emit("success");
            } else {
              ElMessage.error(res.data.msg || "更新失败");
            }
          })
          .catch((error: any) => {
            console.error("更新失败:", error);
            ElMessage.error(
              error.response?.data?.msg || "更新失败，请稍后重试"
            );
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 监听对话框显示
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 延迟执行，确保对话框已经打开
      nextTick(() => {
        openDialog();
      });
    } else {
      // 对话框关闭时重置表单
      if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
      }
    }
  }
);

// 暴露方法
defineExpose({
  openDialog,
});
</script>

<style scoped>
.encasement-dialog__panel :deep(.el-dialog__body) {
  padding: 16px 24px 8px;
}
.encasement-dialog__body {
  padding-bottom: 8px;
}
.encasement-hero {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  padding: 18px 22px;
  border-radius: 16px;
  background: linear-gradient(135deg, #f0f5ff, #f9fbff);
  border: 1px solid #e3e9ff;
  margin-bottom: 18px;
}
.encasement-hero__text {
  flex: 1;
}
.hero-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}
.hero-desc {
  margin: 6px 0 12px;
  color: #5c6b82;
  font-size: 14px;
}
.hero-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.hero-tag {
  border-radius: 999px;
}
.hero-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 120px;
}
.hero-progress__label {
  margin-top: 8px;
  color: #5c6b82;
  font-size: 12px;
}
.form-steps {
  margin-bottom: 18px;
  padding: 12px 16px;
  border-radius: 12px;
  background: #fff;
  border: 1px solid #f0f2f5;
}
.summary-section {
  margin-bottom: 18px;
}
.stat-card {
  border-radius: 14px;
  border: 1px solid #edf1f7;
  background: #fff;
}
.stat-card--accent {
  background: linear-gradient(135deg, #fff7e6, #fff1d6);
  border-color: #ffe5c2;
}
.stat-label {
  margin: 0;
  font-size: 13px;
  color: #909399;
  letter-spacing: 0.5px;
}
.stat-value {
  margin: 8px 0 4px;
  font-size: 28px;
  font-weight: 600;
  color: #1d2129;
  display: flex;
  align-items: baseline;
  gap: 4px;
}
.stat-value--text {
  font-size: 20px;
}
.stat-unit {
  font-size: 14px;
  color: #909399;
}
.stat-desc {
  margin: 0;
  font-size: 12px;
  color: #a0a6b0;
}
.stat-highlight {
  color: #f56c6c;
  font-weight: 600;
}
.encasement-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.encasement-form__alert {
  margin-bottom: -4px;
}
.form-section {
  background: #fdfdfd;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 20px 24px 8px;
  box-shadow: 0 6px 18px rgba(31, 45, 61, 0.05);
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}
.section-header__main {
  display: flex;
  gap: 12px;
  align-items: center;
}
.section-header__icon {
  width: 42px;
  height: 42px;
  border-radius: 10px;
  background: #f0f5ff;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #2f54eb;
}
.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}
.section-subtitle {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.inline-field {
  display: flex;
  align-items: center;
  gap: 10px;
}
.inline-field__label {
  color: #909399;
  font-size: 13px;
  white-space: nowrap;
}
.customer-picker {
  display: flex;
  align-items: center;
  gap: 8px;
}
.customer-picker__btn {
  padding: 6px 10px;
}
.customer-search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}
.customer-search-bar__input {
  flex: 1;
  min-width: 200px;
}
.customer-search-bar__actions {
  display: flex;
  gap: 8px;
  align-items: center;
}
.customer-card {
  border-radius: 12px;
}
.customer-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.customer-card__title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #303133;
}
.customer-card__tips {
  font-size: 12px;
  color: #909399;
}
.customer-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
